/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ch.repit.aglaja.client.contacts;

import ch.repit.rwt.client.Bento;
import ch.repit.rwt.client.BentoDefFactory;
import ch.repit.rwt.client.BentoStatus;
import ch.repit.rwt.client.persistence.CacheManager;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import java.util.List;
import java.util.SortedMap;

/**
 * Only client side (uses CacheManager)
 */
public class AddressUtil {


    /**
     * returns a sorted map of all addresses as keys, and the objectRef as value.
     * Address has the following syntax: country:locality: header / names formated.
     * meant to be used in Select- and MultiSelectField
     */
    public static SortedMap getAddressesSelectMap() {
        SortedMap options = new TreeMap();
        AddressDef addressDef = (AddressDef)BentoDefFactory.get().getDef(AddressDef.TYPE);
        for (Bento a : CacheManager.get().getCachedObjects(AddressDef.TYPE)) {
            List persons = new ArrayList();
            for (Bento p : CacheManager.get().getCachedObjects(PersonDef.TYPE)) {
                if (p.getStatus()==BentoStatus.ACTIVE
                        && p.getDisplayValue(PersonDef.ATTR_ADDRESSREF)!=null
                        && p.getDisplayValue(PersonDef.ATTR_ADDRESSREF).equals(a.getRef().toString()) )
                    persons.add(p);
            }
            String addressDisplay = a.getDisplayValue(AddressDef.ATTR_COUNTRY)+":"
                    +a.getDisplayValue(AddressDef.ATTR_LOCALITY)+": ";
            String slash="";
            if (a.getDisplayValue(AddressDef.ATTR_HEADER) != null
                    && a.getDisplayValue(AddressDef.ATTR_HEADER).trim().length()>0) {
                addressDisplay += a.getDisplayValue(AddressDef.ATTR_HEADER);
                slash=" / ";
            }
            String name = addressDef.formatNames(a, persons);
            if (name != null && name.trim().length()>0)
                addressDisplay += slash+name;

            options.put(addressDisplay, a.getRef().toString());
        }
        return options;
    }

}
